#!/usr/bin/python3
# -*- coding: utf-8; tab-width: 4; indent-tabs-mode: t -*-

import os
import sys
import shutil
import argparse
sys.path.append('/usr/lib/bombyx-mesh')
from byx_util import BymUtil
from byx_param import ByxParam
from byx_daemon import ByxDaemon

# parse parameter
parseResult = None
if True:
    argParser = argparse.ArgumentParser()
    argParser.add_argument("--pid-file", dest='pid_file', help="Specify location of a PID file.")
    argParser.add_argument("-d", "--debug-level", dest='debug_level',
                           choices=['CRITICAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG'], default="INFO",
                           help="Set output debug message level")
    parseResult = argParser.parse_args()

param = ByxParam()

try:
    # fill ByxParam according to argument
    if parseResult.pid_file is not None:
        param.pidFile = parseResult.pid_file
    if param.abortOnError is not None:
        param.abortOnError = parseResult.abort_on_error
    param.logLevel = parseResult.debug_level

    # create logDir
    BymUtil.ensureDir(param.logDir)

    # create tmpDir
    BymUtil.mkDirAndClear(param.runDir)
    BymUtil.mkDirAndClear(param.tmpDir)

    # start server
    param.daemon = ByxDaemon(param)
    param.daemon.run()
finally:
    if os.path.exists(param.tmpDir):
        shutil.rmtree(param.tmpDir)
    if os.path.exists(param.runDir):
        shutil.rmtree(param.runDir)
